//
//  HR_QRCodeViewController.m
//  Pods
//
//  Created by YunPeng-Gao on 2017/7/24.
//
//

#import "HR_QRCodeViewController.h"
#import "HR_QRCodeView.h"
#import "HR_QRCodeCamera.h"


NSString *const AuthorizedString = @"请在iOS - 设置 － 隐私 － 相机 中打开相机权限";
@interface HR_QRCodeViewController ()<CameraDelegate,ScanningViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) UIView *preview;
@property (nonatomic, assign)   BOOL   isLoad;
@property (nonatomic, strong) HR_QRCodeView *scanningView;
@property (nonatomic, strong) HR_QRCodeCamera *camera;
@property (nonatomic, strong) UIImagePickerController *pickerController;

@end

@implementation HR_QRCodeViewController

#pragma mark - ----------   Lifecycle（生命周期） ----------
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    if ([self isCameraIsAuthorized]) {
        if (self.isLoad == YES) {
            [self setupView];
        }
    } else {
        [self cameraAlert:AuthorizedString];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.camera = nil;
    self.preview = nil;
    self.scanningView = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isLoad = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}




#pragma mark - ---------- setup ui ----------
/** 建立视图 */
- (void)setupView {
    [self.scanningView scanning];
    [self.view addSubview:self.preview];
    [self.view addSubview:self.scanningView];
    [self.camera showCaptureOnView:self.preview];
    
}

#pragma mark - SJScanningViewDelegate BarBUttonItem 点击事件
/** 按钮的点击事件 相册 和 手电筒 */
- (void)clickBarButtonItemSJButtonType:(ButtonType)type {
    if (type == ButtonTypeReturn) {
        [self.navigationController popViewControllerAnimated:YES];
    } else if (type == ButtonTypeTorch) {
        [self setTorchMode];
    } else if (type == ButtonTypeAlbum) {
        [self openImagePickerController];
    }
}

#pragma mark - Configuration Torch
/** 配置手电筒 */
- (void)setTorchMode {
    if ([self.camera cameraHasTorch]) {
        [self configurationTorch];
    } else {
        [self cameraAlert:@"您的闪光灯无法开启，请检查!"];
    }
}

#pragma mark - Torch Click
- (void)configurationTorch {
    UIButton *button = [self.scanningView viewWithTag:ButtonTypeTorch];
    button.selected = !button.selected;
    if (button.selected) {
        [self.camera setTorchMode:AVCaptureTorchModeOn];
    } else {
        [self.camera setTorchMode:AVCaptureTorchModeOff];
    }
}

#pragma mark - Open imagePickController
/** 打开相册 */
- (void)openImagePickerController {
    [self presentViewController:self.pickerController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
/** alertMessageString 读取相册中二维码相册的结果*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info; {
    UIImage *pickerImage= [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *resultString = nil;
    if ([[UIDevice currentDevice].systemVersion integerValue] >= 8.0) {
        resultString = [self.camera readAlbumQRCodeImage:pickerImage];
        [picker dismissViewControllerAnimated:YES completion:^{
            NSLog(@"图片扫描结果:%@",resultString);
            [self interfaceResultVCWithResultString:resultString];
        }];
        
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - cammeradelegate
- (void)didDetectCodes:(NSString *)codesString {
    [self.scanningView removeScanningAnimations];
    //    [APP_DELEGATE disPlayHint:codesString];
    [self interfaceResultVCWithResultString:codesString];
}


#pragma mark - 返回结果
- (void)interfaceResultVCWithResultString:(NSString *)resultString {
    self.returnBlock(resultString);
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - The Camera is Authorized
/** 是否授权 */
- (BOOL)isCameraIsAuthorized {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusDenied){
        return NO;
    } else if (authStatus == AVAuthorizationStatusAuthorized) {
        return YES;
    }
    return YES;
}

#pragma mark pravite method
- (void)cameraAlert: (NSString *)msg {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"摄像头不可用" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *openSetting = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:true completion:nil];
    }];
    [alert addAction:cancel];
    [alert addAction:openSetting];
    
    [self presentViewController:alert animated:true completion:nil];
}

#pragma mark - ---------- Lazy Loading（懒加载） ----------
- (HR_QRCodeView *)scanningView {
    if (_scanningView == nil) {
        _scanningView = [[HR_QRCodeView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        _scanningView.scanningDelegate = self;
    }
    return _scanningView;
}

- (UIView *)preview {
    if (!_preview) {
        _preview = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _preview;
}

- (UIImagePickerController *)pickerController {
    if (!_pickerController) {
        _pickerController = [[UIImagePickerController alloc] init];
        _pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _pickerController.delegate = self;
        _pickerController.allowsEditing = NO;
    }
    return _pickerController;
}

- (HR_QRCodeCamera *)camera {
    if (!_camera) {
        _camera = [[HR_QRCodeCamera alloc] init];
        _camera.delegate = self;
    }
    return _camera;
}

#pragma mark - 更改状态栏黑色
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}


#pragma mark -- dealloc
- (void)dealloc {
    [self.camera stopSession];
    self.camera = nil;
    self.preview = nil;
    self.scanningView = nil;
}


@end
